package top.yihoxu.springbootinit.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.Console;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import top.yihoxu.springbootinit.common.BaseResponse;
import top.yihoxu.springbootinit.common.ResultUtils;
import top.yihoxu.springbootinit.model.dto.LoginRequest;
import top.yihoxu.springbootinit.model.vo.CaptchaVO;

import java.io.ByteArrayOutputStream;

/**
 * @Author dth
 * @Date 2024/4/16 20:58
 * @PackageName:top.yihoxu.springbootinit.controller
 * @ClassName: GetController
 * @Description: TODO
 * @Version 1.0
 */
@Slf4j
@RequestMapping("/get")
@RestController
public class GetController {
    @GetMapping("/captcha/image")
    public BaseResponse getCode(HttpSession session) {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        // 将BufferedImage转换为ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //图形验证码写出，可以写出到文件，也可以写出到流
        lineCaptcha.write(outputStream);
        byte[] byteArray = outputStream.toByteArray();
        //字节数组转位Base64
        String base64 = Base64.encode(byteArray);
        String code = lineCaptcha.getCode();
        log.info(base64);
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setBase64(base64);
        session.setAttribute("code", code);
        return ResultUtils.success(captchaVO);

    }

    @PostMapping("/captcha/sendSmsCaptcha")
    public BaseResponse getMsgCode(HttpSession session, @RequestBody LoginRequest loginRequest) {
        String code = (String) session.getAttribute("code");
        if (code != loginRequest.getCaptchaCode()) {
            return ResultUtils.error(500, "验证码错误");
        }
        return null;
    }
}
